#!/bin/sh

studentid='' # 用户名
password=''      # 密码

IP=$(ubus call network.interface.wan status | grep \"address\" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')

function login() {
    #IP="10.73.11.167"
    echo "DDDDD=${studentid}&upass=${password}&R1=0&R2=&R6=0&para=00&0MKKey=123456&buttonClicked=&redirect_url=&err_flag=&username=&password=&user=&cmd=&Login=&R7=0"
    statusfull=$(curl 'http://192.168.167.46/a70.htm' \
        -X POST \
        -H "Cookie: program=ip; vlan=0; md5_login2=${studentid}%7C${password}; ip=${IP}" \
        --data-raw "DDDDD=${studentid}&upass=${password}&R1=0&R2=&R6=0&para=00&0MKKey=123456&buttonClicked=&redirect_url=&err_flag=&username=&password=&user=&cmd=&Login=&R7=0")
    echo "${statusfull}"
    status=$(echo "${statusfull}" | grep -a -oE '<!--Dr.COMWebLoginID_[0-9]\.htm-->')
    echo ${status}
    if [ $status == '<!--Dr.COMWebLoginID_2.htm-->' ]; then
        errormsg=$(echo "${statusfull}" | grep 'msga' | grep -oE "msga='.*'")
        logger -t "校园网认证" "Login Failed:${errormsg}"
        echo "Log Failed:${errormsg}"
        sleep 1
        login
    else
        lasturl=$(echo "${statusfull}" | grep 'UL' | grep -oE "UL='.*'")
        logger -t "校园网认证" "Login Success:${lasturl}"
        
    fi
}
function checkstatus() {
    status=$(curl 'http://192.168.167.46/' \
        -H "Cookie: program=ip; vlan=0; md5_login2=${studentid}%7C${password}; ip=${IP}" | grep 'Dr.COMWebLoginID')
}
# 3成功2失败
function oneloop() {
    checkstatus
    echo ${status}
    if [ $status == '<!--Dr.COMWebLoginID_1.htm-->' ]; then
        echo 'Normal'
        logger 'Normal'
        sleep 1
    else
        logger -t "校园网认证" "Disconnected"
        sleep 13 # 虽然报错是3s，但是实际上应该是13s，猜测是检测10s+冷却3s
        logger -t "校园网认证" "Try to Connect"
        login
        echo 'Logged'
    fi
}

while true; do
    oneloop
done
